import Mock from "mockjs";

const getQuery = (url, name) => {
  const index = url.indexOf("?");
  if (index !== -1) {
    const queryStrArr = url.substr(index + 1).split("&");
    for (var i = 0; i < queryStrArr.length; i++) {
      const itemArr = queryStrArr[i].split("=");
      if (itemArr[0] === name) {
        return itemArr[1];
      }
    }
  }
  return null;
};

const data = Mock.mock({
  "list|20-60": [
    {
      id: "@increment(1)",
      title: "@ctitle",
      content: "@cparagraph",
      add_time: "@date(yyyy-MM-dd hh:mm:ss)",
    },
  ],
});

// 删除
Mock.mock("/api/delete/news", "post", (options) => {
  let body = JSON.parse(options.body);
  const index = data.list.findIndex((item) => item.id === body.id);
  data.list.splice(index, 1);
  return {
    status: 200,
    message: "删除成功",
    list: data.list,
  };
});

// 添加
Mock.mock("/api/add/news", "post", (options) => {
  console.log(options)
  let body = JSON.parse(options.body);
  data.list.push(
    Mock.mock({
      id: "@increment(1)",
      title: body.title,
      content: body.content,
      add_time: "@date(yyyy-MM-dd hh:mm:ss)",
    })
  );
  return {
    status: 200,
    message: "添加成功",
    list: data.list,
  };
});

// 含有分页的数据列表,有需要接受的参数要使用正则匹配
// /api/get/news?pageNum=1&pageSize=10
Mock.mock(/\/api\/get\/news/, "get", (options) => {
  // 获取传递的参数
  const pageNum = getQuery(options.url, "pageNum");
  const pageSize = getQuery(options.url, "pageSize");
  const start = (pageNum - 1) * pageSize;
  const end = pageNum * pageSize;
  const totalPage = Math.ceil(data.list.length / pageSize);
  const list = pageNum > totalPage ? [] : data.list.slice(start, end);
  return {
    status: 200,
    message: "获取成功",
    list,
    total: data.list.length,
  };
});


